<script setup lang="ts">
import { Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch, ref, unref, toRefs, nextTick } from 'vue'
import { ElButton, ElInput } from "element-plus"
import { FormSchema } from '@/types/form'
import { useIcon } from '@/hooks/web/useIcon';
import { Dialog } from '@/components/Dialog'
import { FilesData, ShareData } from "@/api/share/types";
import FileList from '@/views/share/FileList.vue';

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<ShareData>>,
    default: () => null
  },
  formSchema: {
    type: Array as PropType<FormSchema[]>,
    default: () => []
  }
})

const { currentRow } = toRefs(props);

const rules = reactive({})

const { register, methods, elFormRef } = useForm({
  schema: props.formSchema
})

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    const { setValues } = methods
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)
const dialogVisible = ref(false);
const icons = {
  plusIcon: useIcon({ icon: 'ph:plus-bold' })
}
const fileDialogRef = ref<ComponentRef<typeof Dialog>>();
const handleSelectFile = async () => {
  dialogVisible.value = true;
  await nextTick();
  const fileDialog = unref(fileDialogRef);
  fileDialog?.toggleFull();
}

const selectFile = ref<ComponentRef<typeof FileList>>();


const selectedFile = (data: FilesData) => {
  if (currentRow.value) {
    currentRow.value.file_id = data.file_id;
    currentRow.value.file_path = data.file_path;
  }
  dialogVisible.value = false;
}

// const filePathInputRef = ref<ComponentRef<typeof ElInput>>();
// const fileIdInputRef = ref<ComponentRef<typeof ElInput>>();

defineExpose({
  elFormRef,
  getFormData: methods.getFormData
})
</script>

<template>
  <Form :rules="rules" @register="register">
    <template #file_path="form">
      <div class="flex">
        <ElInput ref="filePathInput" v-model="form['file_path']" placeholder="请选择" readonly/>
        <ElInput ref="fileIdInput" v-model="form['file_id']" class="!hidden" placeholder="请选择" />
        <ElButton class="ml-3" :icon="icons.plusIcon" type="primary" @click="handleSelectFile">新增分享文件</ElButton>
      </div>
    </template>
  </Form>
  <Dialog v-if="dialogVisible" ref="fileDialogRef" v-model="dialogVisible" :fullscreen="true" title="选择共享文件">
    <FileList ref="selectFile" @selected="selectedFile" :company-id="currentRow?.company_id" :user-id="currentRow?.user_id"/>
  </Dialog>
</template>
